import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const isAuthenticated = ref(false)
  const user = ref(null)
  const token = ref(null)

  // 从localStorage恢复登录状态
  const initAuth = () => {
    // 优先检查userStore的键名（保持兼容性）
    let savedToken = localStorage.getItem('userToken')
    let savedUser = localStorage.getItem('userInfo')
    
    // 如果没有，则检查authStore自己的键名
    if (!savedToken) {
      savedToken = localStorage.getItem('auth_token')
    }
    if (!savedUser) {
      savedUser = localStorage.getItem('user_info')
    }
    
    if (savedToken && savedUser) {
      token.value = savedToken
      user.value = JSON.parse(savedUser)
      isAuthenticated.value = true
    }
  }

  // 登录
  const login = async (credentials) => {
    try {
      // 这里可以调用实际的API
      token.value = credentials.token
      user.value = credentials.userInfo
      isAuthenticated.value = true
      
      // 同时保存到两套键名（确保兼容性）
      localStorage.setItem('userToken', credentials.token)
      localStorage.setItem('userInfo', JSON.stringify(credentials.userInfo))
      localStorage.setItem('auth_token', credentials.token)
      localStorage.setItem('user_info', JSON.stringify(credentials.userInfo))
      localStorage.setItem('isLoggedIn', 'true')
      
      return true
    } catch (error) {
      console.error('Login failed:', error)
      throw error
    }
  }

  // 注销
  const logout = () => {
    token.value = null
    user.value = null
    isAuthenticated.value = false
    
    // 清除localStorage（所有相关键名）
    localStorage.removeItem('auth_token')
    localStorage.removeItem('user_info')
    localStorage.removeItem('isLoggedIn')
    // 兼容userStore的键名
    localStorage.removeItem('userToken')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('userMode')
  }

  // 检查认证状态
  const checkAuth = () => {
    return isAuthenticated.value && token.value
  }

  return {
    isAuthenticated,
    user,
    token,
    initAuth,
    login,
    logout,
    checkAuth
  }
})